//
//  NewCustomerViewController.m
//  Kfangchan
//
//  Created by liran on 14/11/12.
//  Copyright (c) 2014年 Beijing Renjuren Network Technology Co., Ltd. All rights reserved.
//

#import "NewCustomerViewController.h"
#import "RecommendCustomerViewController.h"

@interface NewCustomerViewController () {

    NSString *sex;
    UIView *addrBookView;
}

@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;

@property (strong, nonatomic) IBOutlet UIView *nameView;
@property (strong, nonatomic) IBOutlet UIView *mobileView;
@property (strong, nonatomic) IBOutlet UIView *idcardView;
@property (strong, nonatomic) IBOutlet UIView *remarkView;
@property (strong, nonatomic) IBOutlet UIView *seeBookView;
@property (strong, nonatomic) IBOutlet UIView *seeBookTimeView;
@property (strong, nonatomic) IBOutlet UIView *seeBookCarView;

@property (strong, nonatomic) IBOutlet UITextField *nameTextField;
@property (strong, nonatomic) IBOutlet UITextField *mobileTextField;
@property (strong, nonatomic) IBOutlet UITextField *idcardTextField;
@property (strong, nonatomic) IBOutlet UITextView *remarkTextView;
@property (strong, nonatomic) IBOutlet UILabel *remarkPlaceHolderLabel;
@property (strong, nonatomic) IBOutlet UISwitch *seeBookSwitch;
@property (strong, nonatomic) IBOutlet UITextField *seeBookTimeTextField;
@property (strong, nonatomic) IBOutlet UISwitch *seeBookCarSwitch;

@property (strong, nonatomic) IBOutlet UIButton *maleButton;
@property (strong, nonatomic) IBOutlet UIButton *femaleButton;



@property (strong, nonatomic) IBOutlet UIButton *recommendButton;


@property (strong, nonatomic) IBOutlet UIView *dateBgView;
@property (strong, nonatomic) IBOutlet UIView *dateView;
@property (strong, nonatomic) IBOutlet UIDatePicker *datePicker;

@end

@implementation NewCustomerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.titleView = [[Theam currentTheam] navigationTitleViewWithTitle:@"推荐客户"];
    self.navigationItem.leftBarButtonItem = [[Theam currentTheam] navigationBarLeftButtonItemWithImage:[UIImage imageNamed:@"nav_back.png"] Target:self Selector:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[Theam currentTheam] navigationBarRightButtonItemWithImage:nil Title:@"历史客户" Target:self Selector:@selector(historyCustomer)];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [tap setNumberOfTouchesRequired:1];
    [self.view addGestureRecognizer:tap];
    
    self.nameView.layer.cornerRadius = 4.0;
    self.mobileView.layer.cornerRadius = 4.0;
    self.idcardView.layer.cornerRadius = 4.0;
    self.remarkView.layer.cornerRadius = 4.0;
    self.seeBookView.layer.cornerRadius = 4.0;
    self.seeBookTimeView.layer.cornerRadius = 4.0;
    self.seeBookCarView.layer.cornerRadius = 4.0;
    
    self.scrollView.size = [UIScreen mainScreen].bounds.size;
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.width, self.recommendButton.origin.y + self.recommendButton.size.height + 80)];
    
    self.dateBgView.frame = theApp.window.bounds;
    self.dateView.origin = CGPointMake(0, ScreenHeight);
    
    self.datePicker.minimumDate = [NSDate date];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self hideKeyboard];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)textViewDidChange:(UITextView *)textView {
    if (self.remarkTextView.text.length == 0) {
        self.remarkPlaceHolderLabel.text = @"填写客户购房需求";
    }else{
        self.remarkPlaceHolderLabel.text = @"";
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [self.remarkTextView resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark -
#pragma mark 性别按钮切换
- (IBAction)chooseSex:(UIButton *)sender{
    int tag = (int)sender.tag;
    if (tag == 2000) {
        self.femaleButton.selected = YES;
        self.maleButton.selected = NO;
        sex = @"女";
    } else {
        self.femaleButton.selected = NO;
        self.maleButton.selected = YES;
        sex = @"男";
    }
}

#pragma mark -
#pragma mark 推荐
- (IBAction)recommend {
    BOOL verify = [self verify];
    if (verify) {
        NSDictionary *param = @{
                                @"name": self.nameTextField.text,
                                @"sex": sex,
                                @"mobile": self.mobileTextField.text,
                                @"idcard": self.idcardTextField.text,
                                @"remark": self.remarkTextView.text,
                                @"seeBook": [NSString stringWithFormat:@"%i", self.seeBookSwitch.on],
                                @"seeBookTime": self.seeBookTimeTextField.text,
                                @"seeBookCar": [NSString stringWithFormat:@"%i", self.seeBookCarSwitch.on],
                                @"buildingId": [NSString stringWithFormat:@"%i", self.buildingId]};
        MKNetworkOperation *operation = [[BaseEngine sharedEngine]RunRequest:[param mutableCopy] path:KFC_RECOMMEND_CUSTOMER_ADD completionHandler:^(id responseObject) {

            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"推荐成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            theApp.reloadCustomerList = YES;
        } errorHandler:^(NSError *error) {
            showCustomAlertMessage(@"网路错误");
        } finishHandler:^(id responseObject) {
            
        }];
        [self.opHandlers addObject:operation];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 表单验证
- (BOOL)verify {
    NSString *name = self.nameTextField.text;
    NSString *mobile = self.mobileTextField.text;
    NSString *idcard = self.idcardTextField.text;
    NSString *remark = self.remarkTextView.text;
    BOOL seeBook = self.seeBookSwitch.on;
    NSString *seeBookTime = self.seeBookTimeTextField.text;
    
    UIAlertView *alert = nil;
    // 姓名
    if (name.length == 0) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入姓名" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    if (name.length > 20) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"姓名限定20字以内" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    // 性别
    if (sex == nil) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择性别" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    // 电话
    if (mobile.length == 0) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入联系方式" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    NSString *regex_phonenum = @"\\d{3}-\\d{8}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{4}-\\d{7}|1+\\d{10}|\\d{7,}";
    NSArray *regexArray = [mobile componentsMatchedByRegex:regex_phonenum];
    if (regexArray.count == 0) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"联系方式格式有误" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    // 身份证(选填)
    if(idcard.length > 0){
        NSString *regex_idcard = @"^(\\d{14}|\\d{17})(\\d|[xX])$";;
        NSArray *regexArray = [idcard componentsMatchedByRegex:regex_idcard];
        if(regexArray.count == 0){
            alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入正确的身份证号" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return NO;
        }
    }
    
    // 备注
    if (remark.length > 200) {
        alert = [[UIAlertView alloc] initWithTitle:nil message:@"备注限定200字以内" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return NO;
    }
    
    // 带看时间
    if (seeBook) {
        if (seeBookTime.length == 0) {
            alert = [[UIAlertView alloc] initWithTitle:nil message:@"请选择带看时间" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return NO;
        }
    }
    
    return YES;
}

#pragma mark -
#pragma mark 关闭键盘
- (IBAction)hideKeyboard {
    [self.nameTextField resignFirstResponder];
    [self.mobileTextField resignFirstResponder];
    [self.idcardTextField resignFirstResponder];
    [self.remarkTextView resignFirstResponder];
}

//-(void)textFieldDidBeginEditing:(UITextField *)textField {
//    [self animateTextField:YES distance:70];
//}
//
//- (void)textFieldDidEndEditing:(UITextField *)textField {
//    [self animateTextField:NO distance:70];
//}
//
//-(void)textViewDidBeginEditing:(UITextView *)textView {
//    [self animateTextField:YES distance:120];
//}
//
//-(void)textViewDidEndEditing:(UITextView *)textView {
//    [self animateTextField:NO distance:120];
//}
//
//- (void)animateTextField:(BOOL)up distance:(int)distance{
//    //设置动画的名字
//    [UIView beginAnimations:@"Animation" context:nil];
//    //设置动画的间隔时间
//    [UIView setAnimationDuration:0.20];
//    //??使用当前正在运行的状态开始下一段动画
//    [UIView setAnimationBeginsFromCurrentState: YES];
//    //设置视图移动的位移
//    float dis = (up ? -distance : distance);
//    self.view.frame = CGRectAddY(self.view.frame, dis);
//    //设置动画结束
//    [UIView commitAnimations];
//}

#pragma mark -
#pragma mark 通讯录按钮蒙窗
- (void)initAddrBookView {
    addrBookView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    addrBookView.backgroundColor = [UIColor clearColor];
    
    UIControl *addrBookControl = [[UIControl alloc] initWithFrame:addrBookView.bounds];
    addrBookControl.backgroundColor = [UIColor blackColor];
    addrBookControl.alpha = 0.4;
    [addrBookControl addTarget:self action:@selector(hideAddrBookControl) forControlEvents:UIControlEventTouchDown];
    [addrBookView addSubview:addrBookControl];
    
    UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(10, [UIScreen mainScreen].bounds.size.height - 90 - 10, 300, 90)];
    buttonView.backgroundColor = [UIColor whiteColor];
    buttonView.layer.cornerRadius = 6.0;
    
    UIView *lineView = [[UIView alloc] init];
    lineView.size = CGSizeMake(buttonView.width, 1);
    lineView.origin = CGPointMake(0, 45);
    lineView.backgroundColor = [UIColor colorWithHexString:@"F0F0F0"];
    [buttonView addSubview:lineView];
    
    UIButton *addrBookButton = [UIButton buttonWithType:UIButtonTypeSystem];
    addrBookButton.frame = CGRectMake(0, 0, buttonView.width, 45);
    [addrBookButton setTitle:@"从通讯录选择" forState:UIControlStateNormal];
    [addrBookButton addTarget:self action:@selector(openAddrBook) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:addrBookButton];
    
    UIButton *otherButton = [UIButton buttonWithType:UIButtonTypeSystem];
    otherButton.frame = CGRectMake(0, 45, buttonView.width, 45);
    [otherButton setTitle:@"直接添加" forState:UIControlStateNormal];
    [otherButton addTarget:self action:@selector(hideAddrBookControl) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:otherButton];
    
    [addrBookView addSubview:buttonView];
}

- (IBAction)showAddrBookControl {
    if (addrBookView == nil) {
        [self initAddrBookView];
    }
    [self hideKeyboard];
    [theApp.window addSubview:addrBookView];
}

- (void)hideAddrBookControl {
    [addrBookView removeFromSuperview];
}

#pragma mark -
#pragma mark 通讯录记录导入
- (void)openAddrBook {
    [self hideAddrBookControl];

    ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
    peoplePicker.peoplePickerDelegate = self;
    [self presentViewController:peoplePicker animated:YES completion:nil];
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    [self dismissViewControllerAnimated:YES completion:nil];
    NSString *firstName =(NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    if (!firstName) {
        firstName = @"";
    }
    NSString *lastName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    if (!lastName) {
        lastName = @"";
    }
    self.nameTextField.text = [NSString stringWithFormat:@"%@%@", lastName, firstName];
    ABMutableMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (ABMultiValueGetCount(phone) > 1) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
        for(int i = 0; i < ABMultiValueGetCount(phone); i++) {
            [sheet addButtonWithTitle:(NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, i))];
        }
        
        [sheet showInView:theApp.window];
        return NO;
    }
    
    NSString *mobile = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, 0));
    self.mobileTextField.text = [mobile stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    return NO;
}

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
    NSString *firstName =(NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    if (!firstName) {
        firstName = @"";
    }
    //firstName = firstName == nil ? @"" : firstName;
    NSString *lastName = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    if (!lastName) {
        lastName = @"";
    }
    //lastName = lastName == nil ? @"" : lastName;
    self.nameTextField.text = [NSString stringWithFormat:@"%@%@", lastName, firstName];
    ABMutableMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    if (ABMultiValueGetCount(phone) > 1) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
        for(int i = 0; i < ABMultiValueGetCount(phone); i++) {
            [sheet addButtonWithTitle:(NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, i))];
        }
        
        [sheet showInView:self.view];
        return;
    }
    
    NSString *mobile = (NSString *)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, 0));
    self.mobileTextField.text = [mobile stringByReplacingOccurrencesOfString:@"-" withString:@""];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (![[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"取消"]) {
        self.mobileTextField.text = [[actionSheet buttonTitleAtIndex:buttonIndex] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    }
}

#pragma mark -
#pragma mark
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 历史客户
- (void)historyCustomer {
    RecommendCustomerViewController *rcv = [[RecommendCustomerViewController alloc] init];
    rcv.buildingId = self.buildingId;
    [self.navigationController pushViewController:rcv animated:YES];
}

#pragma mark -
#pragma mark 是否自行带看切换
- (IBAction)seeBookChange:(UISwitch *)sender {
    float y = 0;
    if (sender.on) {
        self.seeBookTimeView.hidden = NO;
        y = self.seeBookTimeView.origin.y + self.seeBookTimeView.size.height + 8;
    } else {
        self.seeBookTimeView.hidden = YES;
        y = self.seeBookTimeView.origin.y;
    }
    
    __weak NewCustomerViewController *weak_self = self;
    [UIView animateWithDuration:0.5 animations:^{
        weak_self.seeBookCarView.origin = CGPointMake(self.seeBookCarView.origin.x, y);
        weak_self.recommendButton.origin = CGPointMake(self.recommendButton.origin.x, self.seeBookCarView.origin.y + self.seeBookCarView.size.height + 8);
    }];
}

#pragma mark -
#pragma mark 时间选择器
- (IBAction)showDatePicker:(id)sender {
    self.dateBgView.hidden = NO;
    __weak NewCustomerViewController *weak_self = self;
    [UIView animateWithDuration:0.5 animations:^{
        weak_self.dateView.origin = CGPointMake(0, ScreenHeight - weak_self.dateView.size.height - weak_self.navigationController.navigationBar.size.height);
    }];
}

- (IBAction)hideDatePicker:(id)sender {
    __weak NewCustomerViewController *weak_self = self;
    [UIView animateWithDuration:0.5 animations:^{
        weak_self.dateView.origin = CGPointMake(0, ScreenHeight);
    } completion:^(BOOL finished) {
        self.dateBgView.hidden = YES;
    }];
}

- (IBAction)selectDatePicker:(id)sender {
    NSDate *date = [self.datePicker date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    self.seeBookTimeTextField.text = [formatter stringFromDate:date];
    [self hideDatePicker:nil];
}

@end
